<template>
  <div class="replenish-analysis-page">
    <!-- 概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon warning">
              <el-icon size="24"><Warning /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ overview.needReplenish }}</div>
              <div class="card-label">需补货商品</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon danger">
              <el-icon size="24"><CircleClose /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ overview.urgent }}</div>
              <div class="card-label">紧急补货</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon info">
              <el-icon size="24"><Clock /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ overview.planned }}</div>
              <div class="card-label">计划中补货</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon success">
              <el-icon size="24"><TrendCharts /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-value">{{ overview.accuracy }}%</div>
              <div class="card-label">预测准确率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 需求预测图表 -->
    <el-row :gutter="20" style="margin-bottom: 20px">
      <el-col :span="16">
        <el-card>
          <template #header>
            <div class="card-header">
              <h4>需求预测趋势</h4>
              <el-radio-group v-model="forecastPeriod" size="small">
                <el-radio-button label="7">7天</el-radio-button>
                <el-radio-button label="14">14天</el-radio-button>
                <el-radio-button label="30">30天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="forecastChart" style="height: 300px"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card>
          <template #header>
            <h4>补货紧急度分布</h4>
          </template>
          <div ref="urgencyChart" style="height: 300px"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 智能补货建议 -->
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>智能补货建议</h3>
          <div class="header-actions">
            <el-button type="primary" @click="refreshAnalysis">
              <el-icon><Refresh /></el-icon>
              刷新分析
            </el-button>
            <el-button type="success" @click="handleBatchReplenish" :disabled="selectedRows.length === 0">
              <el-icon><DocumentAdd /></el-icon>
              生成补货单（{{ selectedRows.length }}）
            </el-button>
            <el-button @click="exportData">
              <el-icon><Download /></el-icon>
              导出建议
            </el-button>
          </div>
        </div>
      </template>

      <!-- 筛选区域 -->
      <div class="filter-area">
        <el-form :model="filterForm" inline>
          <el-form-item label="仓库">
            <el-select v-model="filterForm.warehouse" placeholder="请选择仓库" clearable style="width: 150px">
              <el-option label="主仓库" value="main" />
              <el-option label="分仓库A" value="branchA" />
              <el-option label="分仓库B" value="branchB" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品分类">
            <el-select v-model="filterForm.category" placeholder="请选择分类" clearable style="width: 150px">
              <el-option label="电子产品" value="electronics" />
              <el-option label="食品饮料" value="food" />
              <el-option label="服装鞋帽" value="clothing" />
              <el-option label="日用百货" value="daily" />
            </el-select>
          </el-form-item>
          <el-form-item label="紧急度">
            <el-select v-model="filterForm.urgency" placeholder="请选择紧急度" clearable style="width: 150px">
              <el-option label="紧急" value="urgent" />
              <el-option label="重要" value="important" />
              <el-option label="普通" value="normal" />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商">
            <el-select v-model="filterForm.supplier" placeholder="请选择供应商" clearable style="width: 150px">
              <el-option label="供应商A" value="supplierA" />
              <el-option label="供应商B" value="supplierB" />
              <el-option label="供应商C" value="supplierC" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetFilter">
              <el-icon><RefreshLeft /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 补货建议表格 -->
      <el-table
        :data="replenishList"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="code" label="商品编码" width="120" />
        <el-table-column prop="name" label="商品名称" min-width="150">
          <template #default="{ row }">
            <div class="product-name">
              <el-image
                :src="row.image"
                style="width: 40px; height: 40px; margin-right: 8px"
                fit="cover"
              />
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="warehouse" label="仓库" width="100" />
        <el-table-column prop="currentStock" label="当前库存" width="100" align="right">
          <template #default="{ row }">
            <el-tag :type="getStockType(row.currentStock, row.safetyStock)">
              {{ row.currentStock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="safetyStock" label="安全库存" width="100" align="right" />
        <el-table-column prop="avgSales" label="日均销量" width="100" align="right" />
        <el-table-column prop="forecastDemand" label="预测需求" width="100" align="right">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; justify-content: flex-end">
              <span>{{ row.forecastDemand }}</span>
              <el-tooltip :content="`预测准确率: ${row.forecastAccuracy}%`" placement="top">
                <el-icon style="margin-left: 5px; color: #409eff; cursor: pointer">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="suggestQty" label="建议补货量" width="120" align="right">
          <template #default="{ row }">
            <el-input-number
              v-model="row.suggestQty"
              :min="0"
              :step="10"
              size="small"
              style="width: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="leadTime" label="采购提前期" width="100" align="center">
          <template #default="{ row }">
            {{ row.leadTime }} 天
          </template>
        </el-table-column>
        <el-table-column prop="estimatedCost" label="预估成本" width="100" align="right">
          <template #default="{ row }">
            ¥{{ row.estimatedCost.toLocaleString() }}
          </template>
        </el-table-column>
        <el-table-column prop="urgency" label="紧急度" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getUrgencyType(row.urgency)">
              {{ row.urgency }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="supplier" label="推荐供应商" width="120" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="viewDetail(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button link type="success" @click="createReplenishOrder(row)">
              <el-icon><DocumentAdd /></el-icon>
              生成补货单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="补货分析详情" width="900px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商品编码">{{ currentDetail.code }}</el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ currentDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="所在仓库">{{ currentDetail.warehouse }}</el-descriptions-item>
        <el-descriptions-item label="当前库存">{{ currentDetail.currentStock }}</el-descriptions-item>
        <el-descriptions-item label="安全库存">{{ currentDetail.safetyStock }}</el-descriptions-item>
        <el-descriptions-item label="最大库存">{{ currentDetail.maxStock }}</el-descriptions-item>
        <el-descriptions-item label="日均销量">{{ currentDetail.avgSales }}</el-descriptions-item>
        <el-descriptions-item label="最近7天销量">{{ currentDetail.sales7Days }}</el-descriptions-item>
        <el-descriptions-item label="最近30天销量">{{ currentDetail.sales30Days }}</el-descriptions-item>
        <el-descriptions-item label="预测需求">{{ currentDetail.forecastDemand }}</el-descriptions-item>
        <el-descriptions-item label="预测准确率">{{ currentDetail.forecastAccuracy }}%</el-descriptions-item>
        <el-descriptions-item label="建议补货量">{{ currentDetail.suggestQty }}</el-descriptions-item>
        <el-descriptions-item label="采购提前期">{{ currentDetail.leadTime }} 天</el-descriptions-item>
        <el-descriptions-item label="推荐供应商">{{ currentDetail.supplier }}</el-descriptions-item>
        <el-descriptions-item label="预估成本">¥{{ currentDetail.estimatedCost }}</el-descriptions-item>
        <el-descriptions-item label="紧急度">
          <el-tag :type="getUrgencyType(currentDetail.urgency)">{{ currentDetail.urgency }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <div style="margin-top: 20px">
        <h4>历史销售趋势</h4>
        <div ref="detailChart" style="height: 250px"></div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button type="primary" @click="createReplenishOrder(currentDetail)">生成补货单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'

// 概览数据
const overview = reactive({
  needReplenish: 45,
  urgent: 12,
  planned: 8,
  accuracy: 87.5
})

// 预测周期
const forecastPeriod = ref('7')

// 筛选表单
const filterForm = reactive({
  warehouse: '',
  category: '',
  urgency: '',
  supplier: ''
})

// 表格数据
const loading = ref(false)
const selectedRows = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const replenishList = ref([
  {
    id: 1,
    code: 'P001',
    name: 'iPhone 14 Pro Max 256GB',
    image: 'https://via.placeholder.com/40',
    warehouse: '主仓库',
    currentStock: 15,
    safetyStock: 30,
    maxStock: 100,
    avgSales: 8,
    sales7Days: 56,
    sales30Days: 240,
    forecastDemand: 84,
    forecastAccuracy: 89,
    suggestQty: 85,
    leadTime: 7,
    estimatedCost: 765000,
    urgency: '紧急',
    supplier: '供应商A'
  },
  {
    id: 2,
    code: 'P002',
    name: '华为 Mate 50 Pro',
    image: 'https://via.placeholder.com/40',
    warehouse: '主仓库',
    currentStock: 22,
    safetyStock: 25,
    maxStock: 80,
    avgSales: 5,
    sales7Days: 35,
    sales30Days: 150,
    forecastDemand: 53,
    forecastAccuracy: 92,
    suggestQty: 58,
    leadTime: 5,
    estimatedCost: 319400,
    urgency: '重要',
    supplier: '供应商B'
  },
  {
    id: 3,
    code: 'P003',
    name: '小米13 Ultra',
    image: 'https://via.placeholder.com/40',
    warehouse: '分仓库A',
    currentStock: 8,
    safetyStock: 20,
    maxStock: 60,
    avgSales: 6,
    sales7Days: 42,
    sales30Days: 180,
    forecastDemand: 62,
    forecastAccuracy: 85,
    suggestQty: 70,
    leadTime: 6,
    estimatedCost: 315000,
    urgency: '紧急',
    supplier: '供应商C'
  },
  {
    id: 4,
    code: 'P004',
    name: 'OPPO Find X6 Pro',
    image: 'https://via.placeholder.com/40',
    warehouse: '主仓库',
    currentStock: 35,
    safetyStock: 30,
    maxStock: 70,
    avgSales: 4,
    sales7Days: 28,
    sales30Days: 120,
    forecastDemand: 40,
    forecastAccuracy: 88,
    suggestQty: 35,
    leadTime: 5,
    estimatedCost: 175000,
    urgency: '普通',
    supplier: '供应商A'
  },
  {
    id: 5,
    code: 'P005',
    name: 'vivo X90 Pro+',
    image: 'https://via.placeholder.com/40',
    warehouse: '分仓库B',
    currentStock: 12,
    safetyStock: 25,
    maxStock: 65,
    avgSales: 7,
    sales7Days: 49,
    sales30Days: 210,
    forecastDemand: 68,
    forecastAccuracy: 90,
    suggestQty: 65,
    leadTime: 6,
    estimatedCost: 390000,
    urgency: '重要',
    supplier: '供应商B'
  }
])

total.value = replenishList.value.length

// 详情对话框
const detailVisible = ref(false)
const currentDetail = ref({})

// 图表引用
const forecastChart = ref(null)
const urgencyChart = ref(null)
const detailChart = ref(null)

// 初始化需求预测图表
const initForecastChart = () => {
  if (!forecastChart.value) return
  
  const chart = echarts.init(forecastChart.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['历史销量', '预测需求', '安全库存线']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['第1天', '第2天', '第3天', '第4天', '第5天', '第6天', '第7天']
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '历史销量',
        type: 'line',
        data: [320, 332, 301, 334, 390, 330, 320],
        smooth: true
      },
      {
        name: '预测需求',
        type: 'line',
        data: [315, 328, 310, 340, 395, 335, 325],
        smooth: true,
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '安全库存线',
        type: 'line',
        data: [250, 250, 250, 250, 250, 250, 250],
        lineStyle: {
          type: 'dashed',
          color: '#F56C6C'
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化紧急度分布图表
const initUrgencyChart = () => {
  if (!urgencyChart.value) return
  
  const chart = echarts.init(urgencyChart.value)
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '紧急度',
        type: 'pie',
        radius: '70%',
        data: [
          { value: 12, name: '紧急', itemStyle: { color: '#F56C6C' } },
          { value: 20, name: '重要', itemStyle: { color: '#E6A23C' } },
          { value: 13, name: '普通', itemStyle: { color: '#409EFF' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
}

// 初始化详情图表
const initDetailChart = () => {
  if (!detailChart.value) return
  
  const chart = echarts.init(detailChart.value)
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['第1周', '第2周', '第3周', '第4周', '第5周', '第6周', '第7周', '第8周']
    },
    yAxis: {
      type: 'value',
      name: '销量'
    },
    series: [
      {
        name: '周销量',
        type: 'bar',
        data: [45, 52, 48, 56, 62, 55, 58, 60],
        itemStyle: {
          color: '#409EFF'
        }
      }
    ]
  }
  chart.setOption(option)
}

// 刷新分析
const refreshAnalysis = () => {
  loading.value = true
  setTimeout(() => {
    ElMessage.success('分析数据已刷新')
    loading.value = false
  }, 1000)
}

// 获取库存类型
const getStockType = (current, safety) => {
  if (current === 0) return 'danger'
  if (current < safety) return 'warning'
  return 'success'
}

// 获取紧急度类型
const getUrgencyType = (urgency) => {
  const map = {
    '紧急': 'danger',
    '重要': 'warning',
    '普通': ''
  }
  return map[urgency] || ''
}

// 选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 查看详情
const viewDetail = (row) => {
  currentDetail.value = { ...row }
  detailVisible.value = true
  nextTick(() => {
    initDetailChart()
  })
}

// 生成单个补货单
const createReplenishOrder = (row) => {
  ElMessageBox.confirm(
    `确认为商品 ${row.name} 生成补货单？建议补货量: ${row.suggestQty}`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success('补货单已生成')
    detailVisible.value = false
  })
}

// 批量生成补货单
const handleBatchReplenish = () => {
  const totalQty = selectedRows.value.reduce((sum, row) => sum + row.suggestQty, 0)
  const totalCost = selectedRows.value.reduce((sum, row) => sum + row.estimatedCost, 0)
  
  ElMessageBox.confirm(
    `确认为选中的 ${selectedRows.value.length} 个商品生成补货单？<br/>总补货量: ${totalQty}<br/>预估总成本: ¥${totalCost.toLocaleString()}`,
    '批量生成补货单',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true
    }
  ).then(() => {
    ElMessage.success('批量补货单已生成')
    selectedRows.value = []
  })
}

// 导出数据
const exportData = () => {
  ElMessage.success('导出成功')
}

// 筛选
const handleFilter = () => {
  loading.value = true
  setTimeout(() => {
    ElMessage.success('查询完成')
    loading.value = false
  }, 500)
}

// 重置筛选
const resetFilter = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  handleFilter()
}

// 分页
const handleSizeChange = (size) => {
  pageSize.value = size
  // 重新加载数据
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  // 重新加载数据
}

// 组件挂载
onMounted(() => {
  nextTick(() => {
    initForecastChart()
    initUrgencyChart()
  })
})
</script>

<style scoped lang="scss">
.replenish-analysis-page {
  padding: 20px;

  .overview-cards {
    margin-bottom: 20px;

    .overview-card {
      .card-content {
        display: flex;
        align-items: center;

        .card-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;

          &.warning {
            background: linear-gradient(135deg, #ffeaa7 0%, #fdcb6e 100%);
            color: #fff;
          }

          &.danger {
            background: linear-gradient(135deg, #ff7675 0%, #d63031 100%);
            color: #fff;
          }

          &.info {
            background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
            color: #fff;
          }

          &.success {
            background: linear-gradient(135deg, #55efc4 0%, #00b894 100%);
            color: #fff;
          }
        }

        .card-info {
          flex: 1;

          .card-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            line-height: 1;
            margin-bottom: 8px;
          }

          .card-label {
            font-size: 14px;
            color: #909399;
          }
        }
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h4 {
      margin: 0;
    }
  }

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
    }

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .filter-area {
    margin-bottom: 20px;
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .product-name {
    display: flex;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

